﻿using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SO.MyMoney.BalanceWebPart
{
    [ToolboxItem(false)]
    public partial class BalanceWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        private void LoadMandatories()
        {
            try
            {
                SPListItemCollection items = Globals.GetMandatories();

                foreach (SPListItem item in items)
                {
                    MandatoryDropDown.Items.Add(new ListItem(item["Title"].ToString(), item[Definitions.FIELD_MANDATORY_NUMBER].ToString()));
                }
            }
            catch(Exception ex)
            {
                ErrorLabel.Text = "Error retrieving mandatories";
            }
            
        }

        private void LoadBalance(int mandatoryid)
        {
            BalanceValue.Text = Globals.GetCurrentBalance(mandatoryid).ToString("C");
        }

        protected void Page_Load(object sender, EventArgs e)
        {   
            if (Globals.IsMultiTenant)
            {
                if (!Page.IsPostBack)
                {
                    LoadMandatories();
                }                
                LoadBalance(int.Parse(MandatoryDropDown.SelectedItem.Value));
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    MandatoryPanel.Visible = false;
                }
                LoadBalance(0);
            }
            
        }

        protected void MandatoryDropDown_SelectedIndexChanged(object sendr, EventArgs e)
        {
            LoadBalance(int.Parse(MandatoryDropDown.SelectedItem.Value));
        }
    }
}
